package com.xp.basic.heima.nio.netty.simpledemo.worker;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

@Slf4j
public class RedisClient {
    static byte[] LINE = {13, 10};//两个字节表示回车，换行
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        //因为 LoggingHandler 带有Shareable 所以是可以线程共享得
        LoggingHandler loggingHandler = new LoggingHandler();
        ChannelFuture channelFuture = new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
//                        ch.pipeline().addLast(loggingHandler);
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
                                buffer.writeBytes("*3".getBytes());
                                buffer.writeBytes(LINE);
                                buffer.writeBytes("$3".getBytes());
                                buffer.writeBytes(LINE);
                                buffer.writeBytes("set".getBytes());
                                buffer.writeBytes(LINE);
                                buffer.writeBytes("$4".getBytes());
                                buffer.writeBytes(LINE);
                                buffer.writeBytes("name".getBytes());
                                buffer.writeBytes(LINE);
                                buffer.writeBytes("$7".getBytes());
                                buffer.writeBytes(LINE);
                                buffer.writeBytes("changlu".getBytes());
                                buffer.writeBytes(LINE);
                                ctx.writeAndFlush(buffer);
//                                super.channelActive(ctx);
                                final ByteBuf writeBuffer = ctx.alloc().buffer();
                                writeBuffer.writeBytes("*2".getBytes());
                                writeBuffer.writeBytes(LINE);
                                writeBuffer.writeBytes("$3".getBytes());
                                writeBuffer.writeBytes(LINE);
                                writeBuffer.writeBytes("get".getBytes());
                                writeBuffer.writeBytes(LINE);
                                writeBuffer.writeBytes("$4".getBytes());
                                writeBuffer.writeBytes(LINE);
                                writeBuffer.writeBytes("name".getBytes());
                                writeBuffer.writeBytes(LINE);
                                ctx.writeAndFlush(writeBuffer);
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                System.out.println(String.format("收到消息为：%s",buf.toString()));
                                byte[] bytes = new byte[buf.capacity()];
//                                buf.readBytes(bytes);
                                buf.writeBytes(bytes);
                                String m = new String(bytes);
                                System.out.println(String.format("msg ：%s",m));
                                log.debug("收到 {} , 消息为：{}", ctx.channel(), buf.toString(Charset.defaultCharset()));
                                super.channelRead(ctx, msg);
                            }
                        });
                    }
                })
                .connect("localhost", 6379)//连接redis
                .sync();//阻塞redis
        Channel channel = channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                System.out.println("已完成");
            }

        }).channel();

        // 向redis 发送数据
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();

        /*//发送数据
        set(buffer);
        channel.writeAndFlush(buffer);
        buffer.clear();
        //获取数据
        get(buffer);
        channel.writeAndFlush(buffer);*/
    }

    //执行set命令：set name changlu
    private static void set(ByteBuf buf){
        buf.writeBytes("*3".getBytes());
        buf.writeBytes(LINE);
        buf.writeBytes("$3".getBytes());
        buf.writeBytes(LINE);
        buf.writeBytes("set".getBytes());
        buf.writeBytes(LINE);
        buf.writeBytes("$4".getBytes());
        buf.writeBytes(LINE);
        buf.writeBytes("name".getBytes());
        buf.writeBytes(LINE);
        buf.writeBytes("$7".getBytes());
        buf.writeBytes(LINE);
        buf.writeBytes("changlu".getBytes());
        buf.writeBytes(LINE);
    }

    //执行get命令：get name
    private static void get(ByteBuf buffer){
        buffer.writeBytes("*2".getBytes());
        buffer.writeBytes(LINE);
        buffer.writeBytes("$3".getBytes());
        buffer.writeBytes(LINE);
        buffer.writeBytes("get".getBytes());
        buffer.writeBytes(LINE);
        buffer.writeBytes("$4".getBytes());
        buffer.writeBytes(LINE);
        buffer.writeBytes("name".getBytes());
        buffer.writeBytes(LINE);
    }
}
